<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.type" placeholder="请输入组织类别" @keyup.enter.native="$refs.table.refresh(true)" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              label="申报体系">
              <a-select
                v-model="queryParam.declarationSystemId"
                :allowClear="true"
                placeholder="请选择申报体系"
                @change="$refs.table.refresh(true)"
              >
                <a-select-option v-for="item in systemList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="setEmpty">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div v-if="!$store.getters.isMzRole" class="table-operator">
      <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button  icon="delete" @click="handleDeleteBatch">删除</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="file" slot-scope="text">
        <!-- <a :href="text?.url" target="_black" :download="text?.original"><ellipsis :length="10" tooltip>{{ text?.original }}</ellipsis></a> -->
        <a @click="$fileDownLoad(text)" v-if="text"><ellipsis :length="10" tooltip>{{ text.original }}</ellipsis></a>
      </span>

      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleCheck(record)">查看</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
          <a-divider type="vertical" />
          <a @click="handleQuota(record)">申报指数</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <check-form
      ref="checkModal"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getCategory, saveCategory, deleteCategory } from '@/api/category'
import { getSystem } from '@/api/system'

import CreateForm from './CreateForm'
import CheckForm from './CheckForm'

let columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '组织类别',
    dataIndex: 'type'
  },
  {
    title: '申报体系',
    dataIndex: 'declarationSystemName'
  },
  {
    title: '排序',
    dataIndex: 'sort'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '考核资料',
    dataIndex: 'file',
    scopedSlots: { customRender: 'file' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'DeclareCategoryList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    CheckForm
  },
  data () {
    // 民政角色不展示操作项
    if (this.$store.getters.isMzRole) {
      columns = columns.filter(v => v.dataIndex != 'action')
    }
    this.columns = columns
    return {
      systemList: [],
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getCategory(requestParameters)
          .then(res => {
            console.log(res)
            return res
          })
      },
      selectedRowKeys: []
    }
  },
  filters: {
  },
  created () {
    this.getSystemList()
  },
  deactivated () {
    this.visible = false
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    setEmpty () {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    getSystemList () {
      getSystem({
        current: 1,
        size: 10000
      }).then(res => {
        this.systemList = res.records
      })
    },
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        deleteCategory({
            id: this.selectedRowKeys.join(',')
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('批量删除成功')
            })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      let assessmentList = []
      if (record.file) {
        const { id, original, url } = record.file
        assessmentList = [{
          uid: id,
          name: original,
          status: 'done',
          url: url
        }]
      }
      this.mdl = { ...record, assessmentList }
      this.visible = true
    },
    handleCheck (record) {
      this.$refs.checkModal.checkView(record)
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteCategory({
            id: record.id
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('删除成功')
            })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          values.fileId = values.assessmentList && values.assessmentList.length > 0 ? values.assessmentList[0].uid : ''
          delete values.assessmentList
          saveCategory(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleQuota (record) {
      this.$router.push({ name: 'DeclareCategoryQuota', query: { socialOrganizationTypeId: record.id } })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
